package db;
import java.sql.*;

import org.apache.log4j.Logger;

import dataService.ServiceClass;

import logic.Config;

public class vhomeDb {
	
	private static Logger log = Logger.getLogger(vhomeDb.class.getName());
	private Connection conn = null; 
	public Connection getConn() {
		return conn;
	}



	
	public vhomeDb() {
		
	// TODO: initialize values from xml configuration file here 	
		
	}
	
	public int init() {
	
		
		try 
		{
			// TODO: add check for using username,pass or in-url user pass
			// TODO: add better error no.s
	       // TODO: Initialize tables using sql file 
		
			log.info("Init vhomeDb");
			Class.forName(Config.driver);
			conn = DriverManager.getConnection(Config.DBurl, Config.userName, Config.password);
			if(conn!=null)
			{return 1;}
			else
			{return 0;}
		}
		catch (ClassNotFoundException e) {
		    // Could not find the database driver
			log.fatal("vhomeDb ClassNotFoundException Cannot find driver: "+Config.driver + " "+e.getStackTrace());
			return -1;
		} catch (SQLException e) {
		    // Could not connect to the database
			log.fatal("vhomeDb SQLException Cannot connect to database: "+Config.driver +","+Config.DBurl+","+Config.userName+","+Config.password+""+e.getStackTrace());
			return -2;
		}
		
	}
	
	public ResultSet select(String query) {
		Statement stmt=null;
		ResultSet rs = null ; 
		try 
		{
		stmt = this.conn.createStatement();
		rs = stmt.executeQuery(query);
		//stmt.close();
		return rs;
		}
		catch(Exception e)
		{

		return null;
		}
	}
	
	
		public int insert(String query) {
			Statement stmt=null;
			int rs = 0 ; 
			try 
			{
			stmt = this.conn.createStatement();
			rs = stmt.executeUpdate(query);
			stmt.close();
			return rs;
			}
			catch(Exception e)
			{
			e.printStackTrace();
			return -1;
			}
	}
	
		public int close()
		{
			try 
			{
			this.conn.close();
			}
			catch(Exception e)
			{
			log.warn("vhomeDb closing Exception: "+e.getStackTrace());
			return 0;	
			}
			
		return 1;
		}
	
}
